package com.yej.aiPolice.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.*
import android.provider.MediaStore
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.core.os.EnvironmentCompat
import com.yej.aiPolice.R
import com.yej.aiPolice.model.beans.User
import com.yej.aiPolice.model.beans.UserFaceInfoBean
import com.yej.aiPolice.presenter.AddFaceActivityPresenter
import com.yej.aiPolice.util.AiPoliceAPP
import com.yej.aiPolice.util.IOUtil
import com.yej.aiPolice.util.UriUtil
import kotlinx.android.synthetic.main.activity_add_face.*
import kotlinx.android.synthetic.main.activity_search_info.tv_user_address
import kotlinx.android.synthetic.main.activity_search_info.tv_user_emg_name
import kotlinx.android.synthetic.main.activity_search_info.tv_user_emg_tel
import kotlinx.android.synthetic.main.activity_search_info.tv_user_name
import kotlinx.android.synthetic.main.activity_search_info.tv_user_tel
import org.jetbrains.anko.toast
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

class AddFaceActivity : AppCompatActivity() {

    private var ivPhoto: ImageView? = null
    private var addFaceActivityPresenter =  AddFaceActivityPresenter(this)
    private var userId:String = ""
    /**
     * 用于保存拍照图片的uri
     */
    private var mCameraUri: Uri? = null
    /**
     * 用于保存图片的文件路径，Android 10以下使用图片路径访问图片
     */
    private var mCameraImagePath: String? = null
    /**
     * 是否是Android 10以上手机
     */
    private val isAndroidQ = Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
    var userFaceInfoBean: UserFaceInfoBean = UserFaceInfoBean()
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_add_face)
        val btCamera =
            findViewById<Button>(R.id.btn_photo)
        val emgCall = findViewById<Button>(R.id.btn_call_emg_tel)
        ivPhoto = findViewById(R.id.iv_search_face)


//        Log.e("创建","调用")
//        tv_user_name.text = "我可以改她"
        btCamera.setOnClickListener(View.OnClickListener { checkPermissionAndCamera() })

    }

    override fun onStart() {
        super.onStart()
        initValue()
        Log.e("人脸","取值"+tv_user_name.text.toString())
    }

    private fun initValue() {
        val Info: User = AiPoliceAPP.sUser
        Log.e("人脸","取值全局"+Info.realname)
        tv_user_name.text = Info.realname
         tv_user_tel.text = Info.tel
        tv_user_address.text =Info.dfAddress
        tv_user_emg_name.text = Info.emgContactName
        tv_user_emg_tel.text  = Info.emgContactNum
    }


    /**
     * 检查权限并拍照。
     * 调用相机前先检查权限。
     */
    private fun checkPermissionAndCamera() {
        val hasCameraPermission = ContextCompat.checkSelfPermission(
            application,
            Manifest.permission.CAMERA
        )
        if (hasCameraPermission == PackageManager.PERMISSION_GRANTED) { //有权限，调起相机拍照。
            openCamera()
        } else { //没有权限，申请权限。
            ActivityCompat.requestPermissions(
                this, arrayOf(Manifest.permission.CAMERA),
                PERMISSION_CAMERA_REQUEST_CODE
            )
            ActivityCompat.requestPermissions(
                this, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                PERMISSION_CAMERA_REQUEST_CODE
            )
        }
    }

    override fun onActivityResult(
        requestCode: Int,
        resultCode: Int,
        data: Intent?
    ) {
        super.onActivityResult(requestCode, resultCode, data)
        Log.e("人脸","地址"+resultCode)
        println("==================resultCode = $resultCode")
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {
                println(mCameraUri)
                ivPhoto!!.setImageURI(mCameraUri)

                val path = UriUtil.getFilePathFromURI(this, mCameraUri)
                var file:File =  File(path);
                var bitMap = IOUtil.readBitmapFromFileDescriptor(path, 200, 200)
                ivPhoto?.setImageBitmap(bitMap)
                Log.e("人脸","地址"+path)
                getValues()
//                Log.e("人脸","地址"+path)
                addFaceActivityPresenter!!.addFace(path,userFaceInfoBean,userId)
            } else {
                Toast.makeText(this, "取消", Toast.LENGTH_LONG).show()
            }
        }
    }


    private fun getValues() {

        Log.e("人脸","地址"+tv_user_name.text.toString())
        userFaceInfoBean.name = tv_user_name.text.toString()
        userFaceInfoBean.tel =  tv_user_tel.text.toString()
        userFaceInfoBean.address =  tv_user_address.text.toString()
        userFaceInfoBean.emgContactName =  tv_user_emg_name.text .toString()
        userFaceInfoBean.emgContactNum =  tv_user_emg_tel.text.toString()
        userFaceInfoBean.criminalRecord = "无"
        userFaceInfoBean.state = "1"
        userId = tv_user_id.text.toString()
        Log.e("人脸","从界面获得的数据id"+userId+"人脸："+userFaceInfoBean.toString())
    }

    /**
     * 处理权限申请的回调。
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        if (requestCode == PERMISSION_CAMERA_REQUEST_CODE) {
            if (grantResults.size > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED
            ) { //允许权限，有调起相机拍照。
                openCamera()
            } else { //拒绝权限，弹出提示框。
                Toast.makeText(this, "拍照权限被拒绝", Toast.LENGTH_LONG).show()
            }
        }
    }

    /**
     * 调起相机拍照
     */
    private fun openCamera() {
        val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        // 判断是否有相机
        if (captureIntent.resolveActivity(packageManager) != null) {
            var photoFile: File? = null
            var photoUri: Uri? = null
            if (isAndroidQ) { // 适配android 10
                photoUri = createImageUri()
            } else {
                try {
                    photoFile = createImageFile()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
                if (photoFile != null) {
                    mCameraImagePath = photoFile.absolutePath
                    println("path = $mCameraImagePath")
                    photoUri =
                        if ( /*Build.VERSION.SDK_INT >= Build.VERSION_CODES.N*/true) { //7.0到9.0
                            //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri 如：content://
                            FileProvider.getUriForFile(
                                this@AddFaceActivity,
                                "com.donkingliang.photograph.fileprovider", photoFile
                            )
                        } else { //7.0以下, 如：file://
                            Uri.fromFile(photoFile)
                        }
                }
            }
            println("photoUri = $photoUri")
            mCameraUri = photoUri
            if (photoUri != null) {
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    val resInfoList = packageManager
                        .queryIntentActivities(captureIntent, PackageManager.MATCH_DEFAULT_ONLY)
                    for (resolveInfo in resInfoList) {
                        val packageName = resolveInfo.activityInfo.packageName
                        grantUriPermission(
                            packageName, photoUri,
                            Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
                        )
                    }
                }
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
                startActivityForResult(
                    captureIntent,
                    CAMERA_REQUEST_CODE
                )
            }
        }
    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     * @return 图片的uri
     */
    private fun createImageUri(): Uri? { //设置保存参数到ContentValues中
        val contentValues = ContentValues()
        //设置文件名
        contentValues.put(
            MediaStore.Images.Media.DISPLAY_NAME,
            System.currentTimeMillis().toString() + ""
        )
        //兼容Android Q和以下版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { //android Q中不再使用DATA字段，而用RELATIVE_PATH代替
//TODO RELATIVE_PATH是相对路径不是绝对路径;照片存储的地方为：内部存储/Pictures/preventpro
            contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, "Pictures/preventpro")
        }
        //设置文件类型
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/JPEG")
        //执行insert操作，向系统文件夹中添加文件
//EXTERNAL_CONTENT_URI代表外部存储器，该值不变
        return contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
    }

    /**
     * 创建保存图片的文件
     * @return
     * @throws IOException
     */
    @Throws(IOException::class)
    private fun createImageFile(): File? {
        val imageName = SimpleDateFormat(
            "yyyyMMdd_HHmmss",
            Locale.getDefault()
        ).format(Date()) + ".jpg"
        //        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//        File storageDir = Environment.getExternalStoragePublicDirectory(
//                Environment.DIRECTORY_PICTURES);
        val storageDir = File(
            Environment.getExternalStorageDirectory().absolutePath
                    + File.separator + "Pictures" + File.separator + "abc"
        )
        if (!storageDir.exists()) storageDir.mkdirs()
        val tempFile = File(storageDir, imageName)
        return if (Environment.MEDIA_MOUNTED != EnvironmentCompat.getStorageState(tempFile)) {
            null
        } else tempFile
    }


    fun onSearchSuccess() {
        toast("添加成功！")
    }


    fun onSearchFail() {
        toast("添加失败！")
    }

    val handler = @SuppressLint("HandlerLeak")
    object : Handler(){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if(msg!!.what == 1){
                val userFaceInfoBean:UserFaceInfoBean = AiPoliceAPP.sFaceInfo;
                tv_user_name.text = userFaceInfoBean.name
                tv_user_tel.text = userFaceInfoBean.tel
                tv_user_address.text = userFaceInfoBean.address
                tv_user_emg_name.text = userFaceInfoBean.emgContactName
                tv_user_emg_tel.text = userFaceInfoBean.emgContactNum
            }

        }
    }


    inner class UpUpdateInfo :Runnable{
        override fun run() {
            handler.sendEmptyMessage(1)
        }

    }


    companion object {
        // 拍照的requestCode
        private const val CAMERA_REQUEST_CODE = 0x00000010
        // 申请相机权限的requestCode
        private const val PERMISSION_CAMERA_REQUEST_CODE = 0x00000012
    }
}